package gsfordservlet.service;

import gsfordservlet.domain.BrokerInfo;
import gsfordservlet.domain.GsfordEvent;
import gsfordservlet.repository.JdbcBrokerInfoDao;
import gsfordservlet.repository.JdbcGsfordEventDao;

import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.List;
import java.util.Random;

import dsm.gsford_broker.EventMulticastMessage;
import dsm.gsford_broker.MessageType;

/**
 *  
 * @author Kyungbaek Kim <kyungbaekkim@gmail.com>
 * @version 2012.0202 (YYYY.MMDD)
 * @since 1.6 (Java Version)
 */
public class GsfordEventManager implements Serializable {
	private static final long serialVersionUID = 4000L;
	    
    private final String defaultBip = "128.195.52.89";
    private final int defaultBport = 6000;
	
	private JdbcGsfordEventDao eventDao;
	private JdbcBrokerInfoDao brokerInfoDao;

	public List<GsfordEvent> getGsfordEvents(){
		return eventDao.getGsfordEventList();		
	}
	
	public void addGsfordEvent(GsfordEvent ge){
		eventDao.addGsfordEvent(ge);
    	sendGsfordEvent(ge);
	}
		
    private void sendGsfordEvent(GsfordEvent ge){
    	String bip = defaultBip;
		int bport = defaultBport;
		Socket socket;
		ObjectOutputStream oos = null;
		
		List<BrokerInfo> brokers = brokerInfoDao.getBrokerInfoList();
		if( brokers != null ){
			int index = new Random().nextInt(brokers.size());
			bip = brokers.get(index).getBip();
			bport = brokers.get(index).getBport();
		}
		
		String sid = bip+":"+ bport;
		
		EventMulticastMessage emm = new EventMulticastMessage(MessageType.MsgEventMulticast, new Random().nextInt(), sid);
		emm.lb_lat = ge.getLblatitude();
		emm.lb_lng = ge.getLblongitude();
		emm.rt_lat = ge.getRtlatitude();
		emm.rt_lng = ge.getRtlongitude();
		emm.text = ge.getMessage()+"\n* Time: "+ge.getDate();
		
		try {
			socket = new Socket(bip, bport);
			if( socket != null ){
				oos = new ObjectOutputStream(socket.getOutputStream());
				if( oos != null ){
					oos.writeObject(emm);
					oos.flush();
					oos.close();
				}
				socket.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		   	
    }
    
	public void setEventDao(JdbcGsfordEventDao ed){
		this.eventDao = ed;
	}
	
	public void setBrokerInfoDao(JdbcBrokerInfoDao bid){
		this.brokerInfoDao = bid;
	}
}
